﻿using Microsoft.Extensions.Logging;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WMS.Model;
using WMS.Repository.IRepository;

namespace WMS.Repository
{
    public class UserRoleRepository : BaseRepository<UserRoleModel>, IUserRoleRepository
    {
        public UserRoleRepository(ISqlSugarClient db, ILogger<UserRoleRepository> logger) : base(db, logger)
        {
        }

        /// <summary>
        /// 获取已经绑定的用户
        /// </summary>
        public async Task<List<UserRoleModel>> BandRoleUserListAsync(long roleId)
        {
            try
            {
                return await _db.Queryable<UserRoleModel>().Where(u => u.RoleId == roleId).ToListAsync();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"获取已绑定用户失败 - 角色ID: {roleId}");
                throw;
            }
        }

        /// <summary>
        /// 绑定用户
        /// </summary>
        public async Task<bool> BandUserAsync(UserRoleModel userRoleModel)
        {
            try
            {
                return await _db.Insertable(userRoleModel).ExecuteCommandAsync() > 0;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"绑定用户失败 - 用户ID: {userRoleModel?.UserId}, 角色ID: {userRoleModel?.RoleId}");
                throw;
            }
        }

        /// <summary>
        /// 解除绑定用户
        /// </summary>
        public async Task<bool> UnBandUserAsync(UserRoleModel userRoleModel)
        {
            try
            {
                return await _db.Deleteable<UserRoleModel>()
                               .Where(u => u.UserId == userRoleModel.UserId && u.RoleId == userRoleModel.RoleId)
                               .ExecuteCommandAsync() > 0;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"解除绑定用户失败 - 用户ID: {userRoleModel?.UserId}, 角色ID: {userRoleModel?.RoleId}");
                throw;
            }
        }

        /// <summary>
        /// 获取用户拥有的角色
        /// </summary>
        public async Task<List<UserRoleModel>> GetUserRoles(long userId)
        {
            try
            {
                return await _db.Queryable<UserRoleModel>().Where(u => u.UserId == userId).ToListAsync();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"获取用户角色失败 - 用户ID: {userId}");
                throw;
            }
        }
    }
}